//创建用户相关的小仓库
import { defineStore } from "pinia";
//引入登陆接口
import { reqLogin, reqLogout, reqUserInfo, mockLogin ,switchLogin} from '@/api/system/user'
import userApi from '@/api/system/user';
//引入数据类型
import type { loginForm } from '@/api/system/user/type'
//引入路由（常量路由）
import router from '@/router';
import { asnycRoute, anyRoute } from "@/router/routers";
//引入深拷贝
import cloneDeep from 'lodash/cloneDeep';
//引入操作本地token工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN, SET_ORGINTOKEN, GET_ORGINTOKEN, REMOVE_ORGINTOKEN, SET_ISMOCK,GET_ISMOCK } from '@/utils/localstore';
//引入树形处理函数
import { processMenu } from '@/utils/processMenu';

//函数，用于过滤用户需要展示的异步路由
function filterAsyncRoute(asnycRoute: any, routes: any) {
    return asnycRoute.filter((item: any) => {
        if (routes.includes(item.name)) {
            if (item.children && item.children.length > 0) {
                item.children = filterAsyncRoute(item.children, routes);
            }
            return true;
        }
    })
}
/// 创建资源报表路由 (单表格和多表格)
const createReportRouters = (userMenu: any) => {
    // 递归查找满足条件的菜单项
    const findTargetMenus = (menus: any[], keys: string[]): any[] => {
        return menus.flatMap(item => {
            const matches = keys.some(key => item[key]) ? [item] : [];
            const childMatches = item.children?.length 
                ? findTargetMenus(item.children, keys) 
                : [];
            return [...matches, ...childMatches];
        });
    };

    // 查找两种报表类型的菜单项
    const [singleTableMenus, multiTableMenus] = [
        findTargetMenus(userMenu, ['forSourceViewId']),
        findTargetMenus(userMenu, ['forSourceReportId'])
    ];

    // 创建路由配置函数
    const createRouteConfig = (menus: any[], componentType: 'single' | 'multi') => {
        // 映射组件路径
        const componentMap = {
            single: () => import('../../views/report/resViewReport/index.vue'),
            multi: () => import('../../views/report/resReports/index.vue')
        };

        return menus.map(item => ({
            path: `/report/view/${item.code}`,
            name: item.code,
            component: componentMap[componentType],
            meta: {
                title: item.name || '资源报表',
                hidden: false,
                type: 2,
                source: {
                    id: item.id,
                    parentId: item.parentId
                }
            }
        }));
    };

    // 生成路由
    const singleTableRoutes = createRouteConfig(singleTableMenus, 'single');
    const multiTableRoutes = createRouteConfig(multiTableMenus, 'multi');

    asnycRoute.push(...singleTableRoutes, ...multiTableRoutes);
    // console.log('已添加资源报表路由:', [...singleTableRoutes, ...multiTableRoutes]);
};


//创建小仓库
const isDark = useDark();
let useUserStore = defineStore('User', {
    //存储数据state
    state: () => {
        return {
            token: GET_TOKEN(), //用户唯一的标识符
            userInfo: {} as any,//存储用户信息                        
            // menuRouters: constantRoute, //仓库存储生成菜单需要的数组（路由）
            isMock: GET_ISMOCK() ? GET_ISMOCK():'false',//是否是mock数据
            orginToken: GET_ORGINTOKEN(),                     
        }
    },
    actions: {
        async userLogin(data: loginForm) {            
            let result = await reqLogin(data) as unknown as string;
            if (result) {
                this.token = result;
                SET_TOKEN(result);                          
                return 'ok';
            } else {
                return Promise.reject(new Error('登录失败'));
            }
        },
        //获取用户信息，比如动态路由的信息
        async getUserInfo() {            
            let result = await reqUserInfo() as unknown as any;
            this.userInfo = result;          
            if (result.menus.length > 0) {
                this.userInfo.userMenu = result.menus[0].children.map((menu: any) => {
                    return processMenu(menu);
                })
            } else {
                this.userInfo.userMenu = [];
            }

            // 角色切换 重置路由表
            router.getRoutes().forEach(route => {
                if(route.meta.type == 2 || route.meta.type == 99){
                    if (route.name) {
                        router.removeRoute(route.name);
                    }
                }
            });
            // 创建动态路由-资源报表
            createReportRouters(this.userInfo.userMenu);

            // 获取用户权限点
            let routes = result.codes;
            // 过滤用户路由                
            let userAsnycRoute = filterAsyncRoute(cloneDeep(asnycRoute), routes);
            [...userAsnycRoute].forEach((route: any) => {
                router.addRoute('layout', route)
            });
            router.addRoute(anyRoute);

           

            // 获取皮肤主题和左侧菜单栏的用户偏好
            this.getFacePref();                        
        },
        async getFacePref() {
            try {
                let results = await userApi.getThemePref({
                    "forPrefInfoId": 1,
                    "code": "theme"
                }) as any;
                if (results) {
                    // 接口调用成功
                    if (results.length > 0 && results[0].prefCombinationDetails && results[0].prefCombinationDetails.length > 0) {
                        let themeVal = results[0].prefCombinationDetails[0].columnValue;
                        if (themeVal != null) {                            
                            isDark.value = themeVal == 'true' ? true : false;                          
                        }
                    }
                } else {
                    // 处理接口调用成功，但返回结果为空的情况
                    throw new Error("接口调用成功，但返回结果为空");
                }
            } catch (error) {
                // 处理接口调用失败的情况
                throw new Error("接口调用失败"); // 返回一个默认值或者进行其他错误处理
            }
        },       
        //退出登录
        async userLogout() {
            try {
                if (this.isMock === 'true') {
                    await reqLogout();
                    this.token = this.orginToken;
                    await reqLogout();
                    this.isMock = 'false';
                    this.orginToken = ''; // 将token重置为空字符串
                    SET_ISMOCK(this.isMock);
                    REMOVE_ORGINTOKEN();
                } else {
                    // 调用 reqLogout 并等待返回结果
                    await reqLogout();
                }
                // 可以在这里处理 logoutResult，例如日志记录等                
            } catch (error) {
                // 处理可能的异常，例如登出请求失败
                console.error("Error during logout:", error);
            } finally {
                if (useDark().value) { // 切换主题
                    useDark().value = !useDark().value;
                }
                REMOVE_TOKEN(); // 清除token，通常用于用户登出流程
                router.push({ path: '/login' }); //跳转登录页
                this.token = ''; // 将token重置为空字符串
                this.userInfo = {} as any; // 将用户信息重置为一个空的UserInfo对象                
            }
        },
        //模拟登录
        async mockLogin(userId: number) {
            try {
                if (this.isMock === 'true' || this.token === '' || this.token === undefined || this.token === null) {
                    return;
                }
                let result = await mockLogin({
                    id: userId,
                    token: this.token
                }) as any
                if (result) {
                    ElMessage.success(`模拟登录成功！`);
                    this.isMock = 'true';
                    this.orginToken = this.token;
                    //防止刷新后isMock、orginToken丢失
                    SET_ORGINTOKEN(this.orginToken);
                    SET_ISMOCK(this.isMock);
                    // 模拟登录成功后，将token存储到本地
                    this.token = result;
                    SET_TOKEN(result);                    
                    // 页面刷新
                    // setTimeout(() => {
                    //     location.reload();
                    // }, 1000);
                    location.reload();
                }
            } catch (error) {
                // 处理接口调用失败的情况
                throw new Error("接口调用失败"); // 返回一个默认值或者进行其他错误处理
            }
        },
        //退出模拟登录
        async mockUserLogout() {
            try {
                // 调用 reqLogout 并等待返回结果
                await reqLogout();
                // 可以在这里处理 logoutResult，例如日志记录等                
            } catch (error) {
                // 处理可能的异常，例如登出请求失败
                ElMessage.error("模拟登出失败！");
            }
            this.token = this.orginToken;
            if (this.token) {
                SET_TOKEN(this.token);
            }
           
            this.isMock = 'false';
            this.orginToken = ''; // 将token重置为空字符串
            SET_ISMOCK(this.isMock);
            REMOVE_ORGINTOKEN();
            // 页面刷新
            location.reload();            
        },
        //切换模拟登录
        async switchMock(userId:number) {
            try {
                if (this.isMock === 'false' || this.orginToken === '' || this.orginToken === undefined || this.orginToken === null) {
                    return;
                }
                let result = await switchLogin({
                    id: userId,
                    token: this.orginToken
                }) as any
                if (result) {
                    ElMessage.success(`模拟登录成功！`);
                    // 模拟登录成功后，将token存储到本地
                    this.token = result;
                    SET_TOKEN(result);
                    
                    // 页面刷新
                    location.reload();                    
                }
            } catch (error) {
                // 处理接口调用失败的情况
                throw new Error("接口调用失败"); // 返回一个默认值或者进行其他错误处理
            }
        },
    },
    getters: {
    }
})

export default useUserStore;
